package com.uyayo.portal.interceptor;

import com.uyayo.cms.entity.CmsSite;
import com.uyayo.framework.common.util.CookieUtils;
import com.uyayo.framework.common.util.MobileUtil;
import com.uyayo.portal.biz.CmsSiteBiz;
import com.uyayo.portal.exception.SiteNotFoundException;
import com.uyayo.portal.vo.CmsSiteVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Interceptor that allows for changing the current locale on every request,
 * via a configurable request parameter (default parameter name: "locale").
 *
 * @author hfj
 * @since 20.06.2017
 * @see WebSiteInterceptor
 */
public class WebSiteInterceptor extends HandlerInterceptorAdapter {

	public static final String SITE_COOKIE = "_site_id_cookie";

	@Autowired
	private CmsSiteBiz cmsSiteBiz;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String server = request.getServerName();
		CmsSiteVO cmsSiteVO = cmsSiteBiz.getCmsSiteByDomain(server);

		if (cmsSiteVO!=null) {
			// 检查重定向
			/*String redirect = cmsSiteVO.getDomainRedirect();
			if (!StringUtils.isEmpty(redirect)) {
				for (String r : redirect.split(",")) {
					if (r.equals(server)) {
						try {
							response.sendRedirect(cmsSiteBiz.getUrl(cmsSite));
						} catch (IOException e) {
							throw new RuntimeException(e);
						}
						return false;
					}
				}
			}*/
			//CookieUtils.addCookie(request, response, SITE_COOKIE, cmsSite.getId().toString(), null, null);

			request.setAttribute("site",cmsSiteVO);
			checkEquipment(request, response);
		}
		if (cmsSiteVO == null) {
			throw new SiteNotFoundException(server);
		}
		return true;
	}



	/**
	 * 检查访问方式
	 */
	public void checkEquipment(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		String ua=(String) session.getAttribute("ua");
		if(null==ua){
			try{
				String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
				if(null == userAgent){
					userAgent = "";
				}
				if(MobileUtil.check(userAgent)){
					ua="mobile";
				} else {
					ua="pc";
				}
				session.setAttribute( "ua",ua);
			}catch(Exception e){}
		}
		if(!StringUtils.isEmpty(ua)){
			request.setAttribute("ua", ua);
		}
	}

	private CmsSite getCmsSiteByCookie(HttpServletRequest request) {
		String cookieValue = CookieUtils.getCookieValue(request, SITE_COOKIE);
		if (!StringUtils.isEmpty(cookieValue)) {
			try {
				Long siteId = Long.valueOf(cookieValue);
				return cmsSiteBiz.getCmsSiteById(siteId);
			} catch (NumberFormatException e) {
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
